package com.example.vehiclefabric.DAO;

import com.example.vehiclefabric.DTO.VehicleBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @name: VehicleDAOImpl
 * @description: 定义车辆密钥保存至数据库的接口的实现。
 * @author: Lulu Zhao
 **/
@Service("vehicleDAOImpl")
public class VehicleDAOImpl implements VehicleDAO {

    @Autowired(required = false)
    private JdbcTemplate jdbcTemplate;

    /**
     * @name: findAll
     * @description: 查询数据库中所有车辆。
     * @params: []
     * @return: java.util.List<com.example.vehiclefabric.DTO.VehicleBean>
     * @author: Lulu Zhao
     */
    @Override
    public List<VehicleBean> findAll() {
        String sql = "select * from vehicle";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(VehicleBean.class));
    }

    /**
     * @name: findByVehicleId
     * @description: 根据车辆ID在数据库中查询车辆。
     * @params: [vehicleId]
     * @return: com.example.vehiclefabric.DTO.VehicleBean
     * @author: Lulu Zhao
     */
    @Override
    public VehicleBean findByVehicleId(String vehicleId) {
        String sql = "select * from vehicle where vehicleId=?";
        Object[] params = new Object[]{vehicleId};
        return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(VehicleBean.class), params);
    }

    /**
     * @name: addVehicle
     * @description: 向数据库中新增车辆。
     * @params: [vehicleBean]
     * @return: boolean
     * @author: Lulu Zhao
     */
    @Override
    public boolean addVehicle(VehicleBean vehicleBean) {
        String sql = "insert into vehicle(vehicleId,KeySM4,KeyHmac) values(?,?,?)";
        Object[] params = {vehicleBean.getVehicleId(), vehicleBean.getKeySM4(), vehicleBean.getKeyHmac()};
        return jdbcTemplate.update(sql, params) > 0;
    }

    /**
     * @name: updateByVehicleId
     * @description: 更新数据库中的车辆信息。
     * @params: [vehicleId, KeySm4, KeyHmac]
     * @return: boolean
     * @author: Lulu Zhao
     */
    @Override
    public boolean updateByVehicleId(String vehicleId, String KeySm4, String KeyHmac) {
        String sql = "update vehicle set KeySM4=?, KeyHmac=? where vehicleId=?";
        Object[] params = {KeySm4, KeyHmac, vehicleId};
        return jdbcTemplate.update(sql, params) > 0;
    }

    /**
     * @name: deleteByVehicleId
     * @description: 根据车辆ID删除数据库中的车辆信息。
     * @params: [vehicleId]
     * @return: boolean
     * @author: Lulu Zhao
     */
    @Override
    public boolean deleteByVehicleId(String vehicleId) {
        String sql = "delete from vehicle where vehicleId=?";
        Object[] params = {vehicleId};
        return jdbcTemplate.update(sql, params) > 0;
    }
}
